const path = require('path')
const packageObj = require('./package.json')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const BeforeHMR = require('./beforeHMR')
const reWriteWatchPack = require('./reWriteWatchPack')
const scopeName = JSON.stringify(packageObj.name)
    // 是否为开发模式
const isDevMode = process.env.NODE_ENV === 'development'
    // 设置访问后台的ip和端口
const requestHost = '47.99.135.166:40502/njgxdc'
const serviceUrl = isDevMode
    ? { // 在开发模式下用的后台ip和端口
        http_base_url: JSON.stringify(`http://${requestHost}`),
        websocket_base_url: JSON.stringify(`ws://${requestHost}/api/${packageObj.name}`)
    }
    : { // 在发布模式下用的ip和端口
        http_base_url: 'location.origin',
        websocket_base_url: `(location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/api/${packageObj.name}"`
    }
const compileMode = process.argv[process.argv.length - 1].slice(2) // 编译模式: dev app lib

const isWatching = isDevMode && process.argv[process.argv.length - 2].slice(2) === 'onWatch'
    // 定义全局变量
const envObj = Object.assign(serviceUrl, {
    APP_SCOPE_NAME: scopeName, // app作用域
    VUE_ROUTER_MODE: JSON.stringify('hash'),
    VUE_ROUTER_BASE: JSON.stringify('/'),
    COMPILE_MODE: JSON.stringify(compileMode)
})

const OUTPUTDIR = `dist/${JSON.parse(scopeName)}`
const RESOURCEPATH = ''

if (isWatching) {
    reWriteWatchPack()
}

module.exports = {
    // publicPath: !isDevMode ? scopeName : '/',
    outputDir: OUTPUTDIR,
    productionSourceMap: false,
    css: {
        extract: false,
        loaderOptions: {
            stylus: {
                import: ['~styles/global/global.styl']
            }
        }
    },
    indexPath: '/index.html',
    configureWebpack: (config) => {
        // config.output.libraryExport = 'default'
        // config.output.libraryTarget = "umd"
        config.module.unknownContextCritical = false

        config.module.rules.push({
            test: /\.(js|vue|ts|tsx|jsx)$/,
            enforce: 'pre',
            exclude: [/lib/, /node_modules/, /dist/, /public/],
            loader: 'eslint-loader',
            options: {
                fix: false,
                extensions: ['.js', '.jsx', '.vue', '.ts', '.tsx'],
                cache: false,
                emitWarning: true,
                emitError: false
            }
        })

        const alias = config.resolve.alias
        Object.assign(alias, {
            'http': path.resolve(__dirname, './src/api/http/'),
            'components': path.resolve(__dirname, './src/components/'),
            'assets': path.resolve(__dirname, './src/statics/assets/'),
            'styles': path.resolve(__dirname, './src/statics/styles/')
        })

        if (!isDevMode) {
            config.externals = {
                'vue': 'Vue',
                'vuex': 'Vuex',
                'vue-router': 'VueRouter'
            }
        }

        config.plugins.push(
            new CopyWebpackPlugin([{
                from: path.resolve(__dirname, 'public'),
                to: path.resolve(__dirname, OUTPUTDIR, RESOURCEPATH),
                ignore: ['.*']
            }])
        )

        config.plugins.push(
            new HtmlWebpackPlugin({
                template: 'public/index.html',
                title: packageObj.productName,
                hash: true
            })
        )

        isWatching && config.plugins.push(
            new BeforeHMR()
        )

        config.performance = {
            hints: 'warning',

            maxEntrypointSize: 50000000,

            maxAssetSize: 30000000,

            assetFilter: function (assetFilename) {
                return assetFilename.endsWith('.js')
            }
        }
    },
    chainWebpack: (config) => {
        // 'src/lib' 目录下为外部库文件，不参与 eslint 检测
        config.module
            .rule('eslint')
            .exclude
            .add('/')
            .end()

        config.plugin('define').tap(args => {
            const processEnv = args[0]['process.env']
            Object.assign(processEnv, envObj)
            return args
        })

        config.plugins.delete('demo-html')
    },

    // 支持 webpack-dev-server 选项，可以访问链接
    // https://webpack.js.org/configuration/dev-server/
    devServer: {
        host: '0.0.0.0',
        port: 8080,
        watchOptions: {
            poll: true,
            aggregateTimeout: 600
        }
    },
    // 构建时开启多进程处理 babel 编译
    parallel: require('os').cpus().length > 1,

    // https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
    pwa: {},

    // 第三方插件配置
    pluginOptions: {
        quasar: {
            theme: 'mat',
            rtlSupport: true,
            importAll: true
        }
    },
    transpileDependencies: [
        /[\\\/]node_modules[\\\/]quasar-framework[\\\/]/,
        /[\\\/]node_modules[\\\/]micro-frontends-server[\\\/]/,
        /[\\\/]node_modules[\\\/]mg-front-end-framework[\\\/]/
    ]
}